//
//  EmailSender.swift
//  App
//
//  Created by 汤泽川 on 2019/3/25.
//

import Foundation
import Vapor
import SwiftSMTP


fileprivate let emailPassword = "pubgnewsbox520"//"newsboxpassword"

fileprivate let smtp = SMTP(hostname: "smtp.163.com",
                            email: "pubgnewsbox@163.com",
                            password: emailPassword)

fileprivate let myEmailUser = Mail.User(name: "短篇小说APP", email: "pubgnewsbox@163.com")

struct EmailSender {
    
    static func sendEmail(_ req:Request,content: EmailContent) throws -> Future<Bool> {
        
        let promise = req.eventLoop.newPromise(Bool.self)
        
        let emailUser = Mail.User(email: content.email)

        let sub = content.subject ?? "Story QA \(TimeManager.current())"
        let text = content.text ?? "欢迎使用Story"

        let mail = Mail(from: myEmailUser,
                        to: [emailUser],
                        subject:sub,
                        text: text)
        
        smtp.send(mail) { (error) in
            if let error = error {
                print("发送失败：",error)
                promise.fail(error: error)
            }else {
                print("发送成功")
                promise.succeed(result: true)
            }
        }
        
        return promise.futureResult
        
    }
}

struct EmailContent : Content {
    var email: String
    var subject: String?
    var text: String?
    init(email : String) {
        self.email = email
    }
}
